//
//  WelcomeViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/10.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SDWebImage

/// 欢迎界面
class WelcomeViewController: UIViewController {
/// 加载视图
    override func loadView() {
        view = backimageView
        setupUI()
    }
    
/// 视图已加载
    /// 异步加载用户头像
    override func viewDidLoad() {
        super.viewDidLoad()
        
        iconView.sd_setImageWithURL(UserAccountViewModel.sharedUserAccount.avatarUrl, placeholderImage: UIImage(named: "avatar_default_big"))
    }
    
/// 视图已显示 播放动画
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        showAnimationByConstrain()
    }
    
    /// 背景图片
    private lazy var backimageView =  UIImageView(imageName: "ad_background")
    /// 头像图片
    private lazy var iconView: UIImageView = {
        let iv = UIImageView(imageName: "avatar_default_big")
        
        //设置圆角
        iv.layer.cornerRadius = 45
        iv.layer.masksToBounds = true
        
        return iv
    }()
    /// 欢迎标签
    private lazy var welcomeLabel: UILabel = UILabel(title: "欢迎回来", textSize: 18)
}

extension WelcomeViewController {
    
/// 设置 UI
    private func setupUI() {
        //添加子控件 头像
        view.addSubview(iconView)
        //设置布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-200)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        //添加子控件 欢迎
        view.addSubview(welcomeLabel)
         welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(16)
        }
    }
    
/// 播放动画
    private func showAnimationByConstrain() {
/// 新约束
        iconView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-view.bounds.height + 200)
        }
        
        welcomeLabel.alpha = 0
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                        // 显示 label
                        self.welcomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootControllerNotification, object: nil)
                })
        }
    }
    
    
}